package com.gameShare.exceptions

import com.gameShare.entity.vo.ResponseVo
import com.gameShare.enums.misc.ResponseCodeEnum
import jakarta.servlet.http.HttpServletRequest
import jakarta.validation.ConstraintViolationException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.MissingServletRequestParameterException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.NoHandlerFoundException
import org.springframework.web.servlet.resource.NoResourceFoundException

@RestControllerAdvice
class GlobalExceptionHandle {

    private val log : Logger = LoggerFactory.getLogger(GlobalExceptionHandle::class.java)

    @ExceptionHandler(Exception::class)
    fun handleException(e: Exception, request: HttpServletRequest): ResponseVo<Nothing> {

        // TODO 处理handleEOFException异常防止机器人参与
        log.debug("请求错误，请求地址({}) 错误信息:", request.requestURL, e)

        val ajaxResponse = ResponseVo<Nothing>()

        when (e) {
            is NoHandlerFoundException, is NoResourceFoundException -> {
                ajaxResponse.code = ResponseCodeEnum.NOT_FIND.code
                ajaxResponse.info = ResponseCodeEnum.NOT_FIND.msg
            }
            is MethodArgumentNotValidException, is HttpRequestMethodNotSupportedException,
            is IllegalStateException, is ConstraintViolationException,
            is MissingServletRequestParameterException-> {
                ajaxResponse.code = ResponseCodeEnum.ARGUMENT_ERROR.code
                ajaxResponse.info = ResponseCodeEnum.ARGUMENT_ERROR.msg
            }
            is BusinessException -> {
                ajaxResponse.code = e.code
                ajaxResponse.info = e.message
            } else -> {
                ajaxResponse.code = ResponseCodeEnum.SERVER_ERROR.code
                ajaxResponse.info = ResponseCodeEnum.SERVER_ERROR.msg
            }
        }
        return ajaxResponse
    }
}